<template>
    <m-navbar :isNeedBack="false" title="登录"/>
    <view class="content-wrap">
        <view class="logo-container w-full flex-col-box flex-justifyCenter-itemsCenter-box box-border">
            <image class="avatar" :src="logoImg"/>
            <view class="w-full mt-20 text-center fz-16">欢迎登录家校通小程序</view>
        </view>

        <view class="mx-10 flex-itemsCenter-box rounded-8 info-box common-shadow box-border mb-12 fz-14">
            <u-input
                class="w-full"
                v-model="loginInfo.phone"
                type="input"
                placeholder="请输入手机号授权登录"
            />
        </view>
        <view class="info-box flex-justifyCenter-itemsCenter-box mx-10">
            <u-button
                class="w-full"
                color="#70B9BE"
                @click="userLogin"
            >
                登录
            </u-button>
        </view>
        <u-toast ref="uToastRef"/>
    </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { wxLogin, LoginParams, getUserInfo } from '@/api/modules/common'

const logoImg = 'https://www.jsjserve.top/static/img/logo.221f1803.png'

const loginInfo: LoginParams = reactive({
	phone: ''
})

const uToastRef = ref(null)

const userLogin = () => {
	if (!loginInfo.phone) {
		uToastRef.value.show({
			type: 'error',
			position: 'bottom',
			message: '请输入手机号',
			iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
		})
	} else if (loginInfo.phone.length !== 11) {
		uToastRef.value.show({
			type: 'error',
			position: 'bottom',
			message: '手机号输入错误',
			iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
		})
	} else {
		uni.showLoading({
			title: '登录中...'
		})
		wxLogin(loginInfo).then(res => {
			if (res.status) {
				uni.setStorageSync('token', res.token)
				uni.setStorageSync('isLogin',  true)
				// 获取用户信息
				getUserInfo().then(userInfo => {
					uni.setStorageSync('userInfo', userInfo.user)
					uni.setStorageSync('roles', userInfo.roles[0])
					uni.hideLoading()
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/announcement/index'
						})
					}, 500)
				})
			} else {
				uToastRef.value.show({
					type: 'error',
					message: res.msg,
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
				})
                uni.hideLoading()
			}
		})
	}
}

</script>

<style scoped lang="scss">
.logo-container {
    height: 600rpx;

    & .avatar {
        width: 110px;
        height: 110px;
    }
}

.info-box {
    margin-top: 40px;
    width: calc(100% - 20px);

    & .icon-chengji {
        font-size: 18px;
    }
}

.iconfont {
    font-size: 34rpx;
}
</style>
